const express = require('express')
const adminRouter = express.Router()
const {md5,encode,decode} = require('../utils')
const adminListModel = require('../db/model/adminListModel')
const checkLogin = require('../middleware/checkLogin')
adminRouter.post('/addAdmin',async (request,response)=>{
    let {adminName,password,rePassword} = request.body
    if(password !== rePassword){
        response.json({
            code:1,
            msg:'两次密码不一致'
        })
    }
    let result = await adminListModel.findOne({adminName})
    if(result){
        response.json({
            code:1,
            msg:'用户已经存在'
        })
    }
    password = md5(password)
    try{
        adminListModel.create({adminName,password})
        response.json({
            code:0,
            msg:'注册成功'
        })
    }catch(e){
        response.json({
            code:2,
            msg:'网络连接异常，请检查'
        })
    }
})

adminRouter.get('/adminList', async (request,response)=>{
    try{
        let adminList = await adminListModel.find({})
        response.json({
            code:0,
            msg:'管理员列表获取成功',
            data:{adminList}
        })
    }catch(e){
        response.json({
            code:2,
            msg:'网络连接异常',
        })
    }
})

adminRouter.get('/deleteAdmin',async (request,response)=>{
    let {_id} = request.query
    try{
        await adminListModel.deleteOne({_id})
        response.json({
            code:0,
            msg:'删除成功'
        })
    }catch(e){
        response.json({
            code:1,
            msg:'删除失败'
        })
    }
})

adminRouter.post('/login',async (request,response)=>{
    let {adminName,password} = request.body
    password = md5(password)

    let result = await adminListModel.findOne({adminName,password}).select({paddword:0}).exec()
    if(result){
        let token = encode({adminName:result.adminName})
        response.json({
            code:0,
            msg:'登录成功',
            data:{token}
        })
    }else{
        response.json({
            code:1,
            msg:'用户名或密码错误'
        })
    }
})

adminRouter.get('/logout',checkLogin,(request,response)=>{
    response.json({
        code:0,
        msg:'退出成功'
    })
})
module.exports = adminRouter